package com.geekaca.news.controller.fore;

import cn.hutool.captcha.ShearCaptcha;
import com.geekaca.news.domain.Link;
import com.geekaca.news.domain.News;
import com.geekaca.news.domain.NewsComment;
import com.geekaca.news.domain.NewsTag;
import com.geekaca.news.service.*;
import com.geekaca.news.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.List;

@Controller
@Slf4j
//@RequestMapping("/news")
public class NewsController {
    public static String theme = "amaze";
    @Autowired
    private NewsService newsService;
    @Autowired
    private ConfigService configService;
    @Autowired
    private TagService tagService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private LinkService linkService;

    // 首页
    @GetMapping({"/", "/index", "index.html"})
    public String index(HttpServletRequest request, HttpSession session) {
        session.setAttribute("keyword", null);
        session.setAttribute("keywordType", null);
        return this.page(session, request, 1);
    }

    @GetMapping("page/{pageNum}")
    public String page(HttpSession session, HttpServletRequest request, @PathVariable("pageNum") int pageNum) {
        List<News> pageNews = newsService.getAllNews(pageNum, 3, null);

        /*pageNews.forEach(news -> {
            String url = news.getNewsCoverImage();
            String localAddr = "";
            if (url.contains("/uploadfile")) {
                String[] url_ = url.split("/uploadfile");
                String shortUrl = "/uploadfile" + url_[url_.length - 1];
                try {
                    localAddr = InetAddress.getLocalHost().getHostAddress();
                    localAddr = "http://"  + localAddr +":" + request.getServerPort() + shortUrl;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            } else {
                String[] url_ = url.split("/admin");
                String shortUrl = "/admin" + url_[url_.length - 1];
                try {
                    localAddr = InetAddress.getLocalHost().getHostAddress();
                    localAddr = "http://"  + localAddr +":" + request.getServerPort() + shortUrl;
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }

            news.setNewsCoverImage(localAddr);
        });*/

        int allNewsCount = newsService.getAllNewsCount(null);
        PageResult pageResult = new PageResult(pageNews, allNewsCount, 3, pageNum);
        List<NewsTag> hotTags = newsService.getHottags();
        List<News> hotBlogs = newsService.getHotNews();
        List<News> newBlogs = newsService.getRecentNews();

        System.out.println("pageNews:" + pageNews);
        request.setAttribute("blogPageResult", pageResult);
        request.setAttribute("newBlogs", newBlogs);
        request.setAttribute("hotBlogs", hotBlogs);
        request.setAttribute("hotTags", hotTags);
        request.setAttribute("pageName", "首页");
        request.setAttribute("pageUrl", "page");

        request.setAttribute("configurations", configService.getConfigMaps());
        return "blog/" + theme + "/index";
    }

    @GetMapping("link")
    public String link(HttpServletRequest request) {
        List<Link> favoriteLinks = linkService.getAllLinks(null, null);
        request.setAttribute("configurations", configService.getConfigMaps());
        request.setAttribute("favoriteLinks", favoriteLinks);
        return "blog/" + theme + "/link";
    }

    @GetMapping("category/**")
    public String categoryMain(HttpServletRequest request) throws UnsupportedEncodingException {

        System.out.println("contextPath: " + request.getRequestURI());
        String requestURI = request.getRequestURI();

        String decodeUri = URLDecoder.decode(requestURI, "UTF-8");
        String[] splitUri = decodeUri.split("/");
        if (splitUri.length == 3) {
            return this.category(request, splitUri[2], 1);
        }
        if (splitUri.length == 4) {
            return this.category(request, splitUri[2], Integer.valueOf(splitUri[3]));
        }
        return null;

    }

    @GetMapping("category/{keyword}/{pageNum}")
    public String category(HttpServletRequest request, @PathVariable("keyword") String keyword,
                           @PathVariable("pageNum") Integer pageNum) {

        List<News> pageNews = newsService.getAllNewsByCategory(pageNum, 3, keyword);
        int allNewsCount = newsService.getNewsCountByCatgeory(keyword);
        PageResult pageResult = new PageResult(pageNews, allNewsCount, 3, pageNum);


        List<NewsTag> hotTags = newsService.getHottags();
        List<News> hotBlogs = newsService.getHotNews();
        List<News> newBlogs = newsService.getRecentNews();

        request.setAttribute("blogPageResult", pageResult);
        request.setAttribute("newBlogs", newBlogs);
        request.setAttribute("hotBlogs", hotBlogs);
        request.setAttribute("hotTags", hotTags);
        request.setAttribute("pageName", "类别结果");
        request.setAttribute("pageUrl", "category" + "/" + keyword);
//        request.setAttribute("keyword", keyword);

        request.setAttribute("configurations", configService.getConfigMaps());

        return "blog/" + theme + "/index";
    }

    @GetMapping("search/{keyword}")
    public String searchTest(HttpServletRequest request,@PathVariable("keyword") String keyword) {

        return this.search(request,keyword,1);
    }

    @GetMapping("search/{keyword}/{pageNum}")
    public String search(HttpServletRequest request, @PathVariable("keyword") String keyword,
                         @PathVariable(value = "pageNum", required = false) Integer pageNum) {

        List<News> pageNews = newsService.getAllNews(pageNum, 3, keyword);
        int allNewsCount = newsService.getAllNewsCount(keyword);
        PageResult pageResult = new PageResult(pageNews, allNewsCount, 3, pageNum);


        List<NewsTag> hotTags = newsService.getHottags();
        List<News> hotBlogs = newsService.getHotNews();
        List<News> newBlogs = newsService.getRecentNews();

        request.setAttribute("blogPageResult", pageResult);
        request.setAttribute("newBlogs", newBlogs);
        request.setAttribute("hotBlogs", hotBlogs);
        request.setAttribute("hotTags", hotTags);
        request.setAttribute("pageName", "搜索结果");
        request.setAttribute("pageUrl", "search" + "/" + keyword);
        request.setAttribute("keyword", keyword);

        request.setAttribute("configurations", configService.getConfigMaps());

        return "blog/" + theme + "/index";
    }


    @GetMapping({"/blog/{newsId}", "/article/{newsId}"})
    public String detail(HttpServletRequest request, @PathVariable("newsId") Long newsId,
                         @RequestParam(value = "commentPage", required = false, defaultValue = "1") Integer commentPage) {
        /**
         * 1, 查询新闻详情， 带出评论
         * 2, 更新新闻的浏览量 + 1
         */
        News newsWithComments = newsService.getById(newsId);
//        int commentCount = commentService.getTotalComentCountByNewsId(newsId);

        PageBean pageBean = new PageBean();
        pageBean.setPageNo(commentPage);
        pageBean.setPageSize(3);
        pageBean.setNewsId(newsId);
        pageBean.setCommentStatus(1);


        PageResult comments = commentService.getCommentsPage(pageBean);


        request.setAttribute("blogDetailVO", newsWithComments);

        request.setAttribute("pageName", "详情");
//        request.setAttribute("comment", comments);
        request.setAttribute("configurations", configService.getConfigMaps());
        request.setAttribute("commentPageResult",comments);
        int updated = newsService.updateNewsViews(newsId);

        return "blog/" + theme + "/detail";
    }

    @GetMapping("tag/**")
    public String tagMain(HttpServletRequest request) throws UnsupportedEncodingException {
        System.out.println("contextPath: " + request.getRequestURI());
        String requestURI = request.getRequestURI();

        String decodeUri = URLDecoder.decode(requestURI, "UTF-8");
        String[] splitUri = decodeUri.split("/");
        if (splitUri.length == 3) {
            return this.tagArticle(request, Integer.valueOf(splitUri[2]), 1);
        }
        if (splitUri.length == 4) {
            return this.tagArticle(request, Integer.valueOf(splitUri[2]), Integer.valueOf(splitUri[3]));
        }
        return null;
    }

    @GetMapping({"/tag/{tagId}/{pageNum}"})
    public String tagArticle(HttpServletRequest request, @PathVariable("tagId") Integer tagId,
                             @PathVariable(value = "pageNum", required = false) Integer pageNum) {

        List<News> pageNews = newsService.selectAllNewsByTagId(tagId, pageNum);
//        int allNewsCount = newsService.selectAllNewsByTagIdCount(tagId, pageNum);
        int allNewsCount = newsService.selectAllNewsByTagIdCount(tagId);

        PageResult pageResult = new PageResult(pageNews, allNewsCount, 3, pageNum);

        System.out.println("pageNews:" + pageNews);

        List<NewsTag> hotTags = newsService.getHottags();
        List<News> hotBlogs = newsService.getHotNews();
        List<News> newBlogs = newsService.getRecentNews();
        request.setAttribute("blogPageResult", pageResult);
        request.setAttribute("newBlogs", newBlogs);
        request.setAttribute("hotBlogs", hotBlogs);
        request.setAttribute("hotTags", hotTags);
        request.setAttribute("pageName", "标签");
        request.setAttribute("pageUrl", "tag" + '/' + tagId);
        request.setAttribute("configurations", configService.getConfigMaps());
        return "blog/" + theme + "/index";
    }

    @GetMapping("/about")
    public String about(HttpServletRequest request){

        return this.detail(request,1L,1);

    }


    @PostMapping(value = "/blog/comment")
    @ResponseBody
    public Result comment(HttpServletRequest request, HttpSession session,
                          @RequestParam Long newsId, @RequestParam String verifyCode,
                          @RequestParam String commentator,
                          @RequestParam String email,
                          @RequestParam String websiteUrl, @RequestParam String commentBody) {
        if (!StringUtils.hasText(verifyCode)) {
            return ResultGenerator.genFailResult("验证码不能为空");
        }

        ShearCaptcha shearCaptcha = (ShearCaptcha) session.getAttribute("verifyCode");
        if (shearCaptcha == null || !shearCaptcha.verify(verifyCode)) {
            return ResultGenerator.genFailResult("验证码错误");
        }

        String ref = request.getHeader("Referer");
        if (!StringUtils.hasText(ref)) {
            return ResultGenerator.genFailResult("非法请求");
        }

        if (null == newsId || newsId < 0) {
            return ResultGenerator.genFailResult("非法请求");
        }

        if (!StringUtils.hasText(commentator)) {
            return ResultGenerator.genFailResult("请输入称呼");
        }

        if (!StringUtils.hasText(email)) {
            return ResultGenerator.genFailResult("请输入邮箱地址");
        }

        if (!PatternUtil.isEmail(email)) {
            return ResultGenerator.genFailResult("请输入正确的邮箱地址");
        }
        if (!StringUtils.hasText(commentBody)) {
            return ResultGenerator.genFailResult("请输入评论内容");
        }
        if (commentBody.trim().length() > 200) {
            return ResultGenerator.genFailResult("评论内容过长");
        }

        NewsComment comment = new NewsComment();
        comment.setNewsId(newsId);
        comment.setCommentator(MyBlogUtils.cleanString(commentator));
        comment.setEmail(email);
        if (PatternUtil.isURL(websiteUrl)) {
            comment.setWebsiteUrl(websiteUrl);
        }
        comment.setCommentBody(MyBlogUtils.cleanString(commentBody));
        return ResultGenerator.genSuccessResult(commentService.addComment(comment));


    }


    // 传递集合
    @RequestMapping("/all")
    public String getAll(HttpServletRequest req) {
        List<News> allNews = newsService.getAllNews();
        req.setAttribute("all", allNews);

        return "newsList local all";
    }

    // 单个值传递
    @GetMapping("/toPage")
    public String toPage(HttpServletRequest req) {

        req.setAttribute("usagi", "obaasann");
        req.setAttribute("date", "nithiyobi");
        req.setAttribute("Month", 3);
        return "hello local conflicts.";
    }

    // 从控制器向页面传递对象  
    @GetMapping("/newsDetail/{newsID}")
    public String toDetail(HttpServletRequest request, @PathVariable("newsID") Long newsID) {
        News news = newsService.getById(newsID);
        request.setAttribute("newsInfo", news);
        return "newsDetail";
    }
}
